package cn.cvs.web;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SysUserContext {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysRoleService sysRoleService;

    @RequestMapping(value = {"/","/toLogin"})
    public String toLogin(){
        return "login";
    }

    /**
     * 登录
     * SysUser user  使用对象  要求提交的属性名与封装的对象有相同字段
     * user.getAccount(),user.getPassword()
     */
    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, Model model, HttpSession session){
        SysUser sysUser = sysUserService.queryByAccountAndPassword(account, password);
        if (sysUser!=null){
            //登录成功
            //将登录用户保存到session中
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "frame";
        }else{
            //登录失败
            //绑定错误消息,跳转到登录页面
            model.addAttribute("error","用户名或密码错误");
            //return "login";
            //转发请求
            return "forward:/toLogin";
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String duLoginOut(HttpSession session){
        System.out.println(session.getAttribute("userSession"));
        session.removeAttribute("userSession");//移除指定的属性
        System.out.println(session.getAttribute("userSession"));
        return "forward:/toLogin";
    }

    /**
     * 异常处理方法
     * 当前控制器SysUserContext抛出的异常
     * 都会交给这个方法处理
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    public String exceptionMethod(Exception e, Model model){
        //打印异常的堆栈信息
        e.printStackTrace();
        model.addAttribute("exception",e);
        return "sysError";
    }

    /**
     * 返回主页
     * @return
     */
    @RequestMapping("/sys/toMain")
    public String toMain(){
        return "frame";
    }

    /**
     * 查询用户列表
     * 输入:入参  客户端(页面)传递给后台数据
     * 输入:出参 后台传递给客户端(页面)的数据
     *对于前后台不分离的系统 这种数据存储在作用域中
     * 我们用的jsp name出参就是el表达式中的数据
     */
    @RequestMapping("/sys/user/list")
    public String list(@RequestParam(value = "queryRealName",required = false) String realName,
                       @RequestParam(value = "queryRoleId",required = false)Integer roleId,
                       @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo,
                       Model model){

        //出参queryRealName
        model.addAttribute("queryRealName",realName);
        //出参queryRoleId
        model.addAttribute("queryRoleId",roleId);
        //出参roleList所有的角色
        List<SysRole> sysRoles = sysRoleService.queryAll();
        model.addAttribute("roleList",sysRoles);
        //出参userList用户列表
        List<SysUser> sysUsers = sysUserService.queryByPage(realName, roleId, pageNo, Constants.pageSize);
        model.addAttribute("userList",sysUsers);
        //出参totalCount总记录数
        int count = sysUserService.queryByPageCount(realName, roleId);
        model.addAttribute("totalCount",count);
        //出参currentPageNo当前页码 等于 pageNo
        model.addAttribute("currentPageNo",pageNo);
        //出参totalPageCount总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(Constants.pageSize);
        pageSupport.setTotalCount(count);
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "sysUser/list";
    }


    /**
     * 跳转到添加用户界面
     * @param model
     * @return
     */
    @RequestMapping("/sys/user/toAdd")
    public String addSysUser(@ModelAttribute("sysUser") SysUser sysUser, Model model){
        //roleList所有的角色
        List<SysRole> sysRoles = sysRoleService.queryAll();
        model.addAttribute("roleList",sysRoles);
        //@ModelAttribute("sysUser") SysUser sysUser或
        //model.addAttribute("sysUser",new SysUser());
        return "sysUser/add";
    }

    /**
     * 添加用户
     * @Valid SysUser sysUser, BindingResult bindingResult
     * 后台验证
     * BindingResult必须写在实体类的后面
     * @RequestParam(value = "idPic",required = false) MultipartFile idPic上传文件
     */
    /**@PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session, HttpServletRequest request, Model model,
                          @RequestParam(value = "idPic",required = false) MultipartFile idPic){
        //登录判断
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            model.addAttribute("error","请登录后操作");
            return "login";
        }
        //查看后台验证的结果
        if(bindingResult.hasErrors()){
            //效验出错误,不能通过
            //回数据添加的页面,会自动带上错误消息
            throw new RuntimeException("数据效验错误");
            //return  "sysUser/add";
        }
        //上传文件的核心代码
        //图片命名规则
        //时间戳(毫秒数)_图片的原名  long l = System.currentTimeMillis();
        String saveFileName=System.currentTimeMillis()+"_"+idPic.getOriginalFilename();//getOriginalFilename获取原始文件名
        //保存到服务器上的路径  File.separator:分隔符 /
        String dirPath=
            request.getSession().getServletContext().getRealPath("statics"+ File.separator +"uploadFiles");
        //服务器根目录的物理路径
        //服务器根目录/static/uploadFiles/..
        File dir=new File(dirPath);
        if (!dir.exists()) {
            //如果这个目录不存在就创建
            dir.mkdirs();
        }
        //idPic.transferTo(new file("服务器保存文件的路径"))
        File saveFile=new File(dir,saveFileName);//将saveFileName这个文件放入到dir目录中
        try {
            idPic.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("图片上传失败",e);
        }
        //向数据库保存图片的信息
        //保存一个逻辑路径,方便在其他地方引用
        String idPicPath=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
        sysUser.setIdPicPath(idPicPath);//保存逻辑路径


        //创建时间
        sysUser.setCreatedTime(new Date());
        //创建人id
        sysUser.setCreatedUserId(attribute.getId());
        int i = sysUserService.addUser(sysUser);
        if (i>0) {
            //添加用户成功
            //重定向回用户列表
            return "redirect:/sys/user/list";
        }else{
            throw new RuntimeException("添加用户失败");
        }
    }*/
    //上传多文件
    @PostMapping("/sys/user/add")
    public String addUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session, HttpServletRequest request, Model model,
                          @RequestParam(value = "attaches",required = false) MultipartFile[] attaches){
        //登录判断
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            model.addAttribute("error","请登录后操作");
            return "login";
        }
        //查看后台验证的结果
        if(bindingResult.hasErrors()){
            //效验出错误,不能通过
            //回数据添加的页面,会自动带上错误消息
            throw new RuntimeException("数据效验错误");
            //return  "sysUser/add";
        }

        for (int i = 0; i < attaches.length; i++) {
            //上传文件的核心代码
            //图片命名规则
            //时间戳(毫秒数)_图片的原名  long l = System.currentTimeMillis();
            String saveFileName=System.currentTimeMillis()+"_"+attaches[i].getOriginalFilename();//getOriginalFilename获取原始文件名
            //保存到服务器上的路径  File.separator:分隔符 /
            String dirPath=
                    request.getSession().getServletContext().getRealPath("statics"+ File.separator +"uploadFiles");
            //服务器根目录的物理路径
            //服务器根目录/static/uploadFiles/..
            File dir=new File(dirPath);
            if (!dir.exists()) {
                //如果这个目录不存在就创建
                dir.mkdirs();
            }
            //idPic.transferTo(new file("服务器保存文件的路径"))
            File saveFile=new File(dir,saveFileName);//将saveFileName这个文件放入到dir目录中
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("图片上传失败",e);
            }
            //向数据库保存图片的信息
            //保存一个逻辑路径,方便在其他地方引用
            String picPath=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
            if(i==0){
                //设置身份照
                sysUser.setIdPicPath(picPath);
            }else{
                //设置工作照
                sysUser.setWorkPicPath(picPath);
            }
        }
        //创建时间
        sysUser.setCreatedTime(new Date());
        //创建人id
        sysUser.setCreatedUserId(attribute.getId());
        int i = sysUserService.addUser(sysUser);
        if (i>0) {
            //添加用户成功
            //重定向回用户列表
            return "redirect:/sys/user/list";
        }else{
            throw new RuntimeException("添加用户失败");
        }
    }

    /**
     * 异步请求
     * 检查account是否重名
     */
    @ResponseBody  //标识这是一个ajax
    @GetMapping("/sys/user/userExist")
    public Object userExists(String account){
        //返回值map
        Map<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist",-1);
            resultMap.put("msg","用户不能为空");
            return JSON.toJSONString(resultMap);
        }

        try {
            int userExist = sysUserService.queryUserExist(account);
            if (userExist>0) {
                //不可用1
                resultMap.put("exist","1");
            }else{
                //可用0
                resultMap.put("exist","0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("exist","-1");
            resultMap.put("msg",e.getMessage());
        }
        return JSON.toJSONString(resultMap);
    }


    /**
     * 跳转到修改页面
     */
    @RequestMapping("/sys/user/toUpdate")
    public String toUpdateUser(@RequestParam("uid") Integer id, Model model){
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        //角色列表
        List<SysRole> sysRoles = sysRoleService.queryAll();
        model.addAttribute("sysRoles",sysRoles);
        return "sysUser/update";
    }

    /**
     * 修改用户
     */
    @PostMapping("/sys/user/update")
    public String updateUser(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session){
        //登录验证
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            throw new RuntimeException("请登录后操作");
        }
        //效验后台数据
        if (bindingResult.hasErrors()) {
            return "sysUser/update";
        }

        //修改时间
        sysUser.setUpdatedTime(new Date());
        //修改人id
        sysUser.setUpdatedUserId(attribute.getId());
        //修改用户信息
        int i = sysUserService.updateTrim(sysUser);
        if (i>0){
            return "redirect:/sys/user/list";
        }else{
            throw new RuntimeException("修改用户失败,请稍后再试");
        }
    }

    /**
     * 同步请求
     * 查看指定用户信息
     */
    @GetMapping("/sys/user/view/{uid}")
    public String viewUSer(@PathVariable("uid") Integer id, Model model){
        SysUser sysUser = sysUserService.queryById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }
    /**
     * 异步查看用户信息
     * /sys/user/{uid}/view
     * @PathVariable("uid")
     * 获取请求中所带的值
     */
    @ResponseBody
    @GetMapping("/sys/user/{uid}/view")
    public Object viewUsers(@PathVariable("uid") Integer id){
        //返回值对象
        DataTransfer<SysUser> dto = new DataTransfer<SysUser>();
        try {
            if (id==null) {
                dto.setStatus("failed");
                return JSON.toJSONString(dto);
            }
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser==null) {
                dto.setStatus("nodata");
                return JSON.toJSONString(dto);
            }
            //查询成功
            dto.setStatus("ok");
            dto.setData(sysUser);
            return JSON.toJSONString(dto);
        } catch (Exception e) {
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }


    /**
     * 异步请求
     * 删除用户
     */
    @ResponseBody
    //@GetMapping("/sys/user/del/{userid}")
    @DeleteMapping(value="/sys/user/{uid}")
    public Object deleteUser(@PathVariable("uid")Integer id, HttpSession session, HttpServletRequest request){
        Map<String,Object> resultMap=new HashMap<String,Object>();//返回值对象
        try {
            SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);//登录检查
            if (loginUser==null) {
                resultMap.put("delResult","noLogin");
                resultMap.put("msg","请登录后操作");
                return JSON.toJSONString(resultMap);
            }
            //参数非空判断
            if (id==null) {
                resultMap.put("delResult","error");
                resultMap.put("msg","参数错误");
                return JSON.toJSONString(resultMap);
            }
            //非管理员不能删除
            if (loginUser.getRoleId()!=1) {
                resultMap.put("delResult","notadmin");
                resultMap.put("msg","非管理员不能删除");
                return JSON.toJSONString(resultMap);
            }

            //依据id查询要删除的用户
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser==null) {
                resultMap.put("delResult","notexist");
                return JSON.toJSONString(resultMap);
            }

            //不能删除管理员
            if (sysUser.getRoleId()==1) {
                resultMap.put("delResult","deladmin");
                resultMap.put("msg","不能删除管理员");
                return JSON.toJSONString(resultMap);
            }

            //删除用户
            int delete = sysUserService.deleteById(id,request);
            if (delete>0) {
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("delResult","error");
            resultMap.put("msg","系统繁忙,请稍后再试");
            return JSON.toJSONString(resultMap);
        }
    }

    /**
     * 跳转修改用户密码
     */
    @RequestMapping("sys/user/toUpdatePwd")
    public String toUpdatePwd(){
        return "sysUser/updatePassword";
    }

    /**
     * 验证旧密码是否正确
     */
    @ResponseBody
    @PostMapping("/sys/user/checkOldPwd")
    public Object checkOldPwd(String oldPassword, HttpSession session){
        //保存结果
        Map<String,Object> resultMap=new HashMap<String,Object>();
        try {
            //获取用户信息
            SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
            //判断用户是否已经登录
            if (sysUser==null) {
                resultMap.put("result","sessionerror");
                return JSON.toJSONString(resultMap);
            }
            //判断密码是否为空
            if (oldPassword.equals("")) {
                resultMap.put("result","error");
                return JSON.toJSONString(resultMap);
            }
            //获当前登录用户密码
            String password = sysUser.getPassword();
            if (password.equals(oldPassword)) {
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result","error");
            return JSON.toJSONString(resultMap);
        }
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/user/savePassword")
    public String savePassword(@RequestParam(value = "newPassword",required = false) String newPassword,
                               HttpSession session){
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        //判断用户是否已登录
        if(sysUser==null){
            //转发到登录或  return "login";
            return "forward:/toLogin";
        }
        //修改密码
        sysUser.setPassword(newPassword);
        sysUser.setUpdatedTime(new Date());
        sysUser.setUpdatedUserId(sysUser.getId());
        int update = sysUserService.updateTrim(sysUser);
        if (update>0) {
            //退出重新登录
            return "forward:/logout";
        }else{
            throw new RuntimeException("修改密码失败");
        }
    }

    /**
     * 获取角色列表
     */
    @ResponseBody
    @GetMapping("/sys/role/simpleList")
    public Object simpleList(){
        List<SysRole> sysRoles = sysRoleService.queryAll();
        return JSON.toJSONString(sysRoles);
    }



}